package com.hankol.material

import android.annotation.SuppressLint
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.download.DownloadInfo
import com.baselibrary.db.DBManager
import com.baselibrary.manager.LoadingManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.net.APIResponse
import com.baselibrary.permission.PermissionCollection
import com.baselibrary.permission.PermissionsUtils
import com.baselibrary.permission.callback.PermissionsCall
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.hankol.material.api.MaterialConstants
import com.hankol.material.bean.CreateFolderBean
import com.hankol.material.bean.FolderListBean
import com.hankol.material.bean.MaterialContentInfo
import com.hankol.material.bean.TabConfigure
import com.hankol.material.databinding.ActivityMaterialDocumentDetailBinding
import com.hankol.material.limit.DownloadLimitManager
import com.hankol.material.viewmodel.DocumentDetailViewModel
import com.wdeo3601.pdfview.PDFView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

/**文档详情
 * @author: merbng
 * @time: 2021/10/15 10:02
 * @description:
 */
@Route(path = ActivityRouter.MATERIAL.DOCUMENT_DETAIL)
class DocumentDetailActivity : BaseActivity(), View.OnClickListener {

    private lateinit var viewModel: DocumentDetailViewModel
    private lateinit var binding: ActivityMaterialDocumentDetailBinding
    private lateinit var bean: MaterialContentInfo.FileLibsBean.DataBean
    private lateinit var mSensorsDataManager: SensorsDataManager

    override fun getLayoutId(): Int {
        return R.layout.activity_material_document_detail
    }


    @SuppressLint("SetJavaScriptEnabled")
    override fun init() {
        mSensorsDataManager = SensorsDataManager.instance
        mSensorsDataManager.onCreateTime()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
        StatusBarUtil.setTranslucentStatus(this)
        binding = getDataBinding()
        viewModel = getActivityViewModelProvider(this).get(DocumentDetailViewModel::class.java)
        LoadingManager.showLoadingDialog(this)
        binding.backImageView.setOnClickListener(this)
        val webSettings = binding.webView.settings
        webSettings.javaScriptEnabled = true
        webSettings.allowFileAccess = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.defaultZoom = WebSettings.ZoomDensity.CLOSE
        webSettings.loadWithOverviewMode = true//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.setAppCacheEnabled(true)//是否使用缓存
        webSettings.domStorageEnabled = true//DOM Storage
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        // 启用数据库
        webSettings.databaseEnabled = true
        webSettings.useWideViewPort = true
        webSettings.setSupportZoom(true)
        webSettings.builtInZoomControls = true;
        webSettings.allowUniversalAccessFromFileURLs = true
        binding.webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                LoadingManager.hideLoadingDialog(this@DocumentDetailActivity)
            }
        }
//        binding.webView.getSettings().setTextZoom(100)

        if (intent.hasExtra(Constants.KEY_DOCUMENT_BEAN)) {
            bean = intent.getSerializableExtra(Constants.KEY_DOCUMENT_BEAN) as MaterialContentInfo.FileLibsBean.DataBean
            //是否收藏
            binding.imgCollectCancel.isSelected = bean.isHasCollect == 1
            //是否已下载过
            isAlwaysDownload()
            binding.tvTitle.text = "${bean.name}.${bean.desc}"

            if (bean.fileUrl.contains("pdf")) {
                binding.pdfView.visibility=View.VISIBLE
                binding.webView.visibility=View.GONE
                // 设置当前显示页的前后缓存个数，效果类似 ViewPager 的这个属性
                binding.pdfView.setOffscreenPageLimit(2)
// 是否支持缩放
                binding.pdfView.isCanZoom(true)
// 设置最大缩放倍数,最大支持20倍
                binding.pdfView.setMaxScale(10f)
// 设置当前页变化的回调监听
                binding.pdfView.setOnPageChangedListener(object : PDFView.OnPageChangedListener {
                    @SuppressLint("SetTextI18n")
                    override fun onPageChanged(currentPageIndex: Int, totalPageCount: Int) {
                        // show current page number
                    }
                })
// 从本地文件打开 pdf
//                binding.  pdfView.showPdfFromPath(filePath)
// 从网络打开 pdf
                binding.pdfView.showPdfFromUrl(bean.fileUrl)
                LoadingManager.hideLoadingDialog(this@DocumentDetailActivity)
            } else {
                binding.webView.visibility=View.VISIBLE
                binding.pdfView.visibility=View.GONE
                binding.webView.loadUrl(if (bean.fileUrl.contains("pdf")) "${"file:///android_asset/generic/web/viewer.html?file=${bean.fileUrl}"}" else "https://view.officeapps.live.com/op/embed.aspx?src=${bean.fileUrl}")
            }
            binding.tvOpen.setOnClickListener(this)
            binding.tvDownload.setOnClickListener(this)
            binding.tvShare.setOnClickListener(this)
            binding.llCollect.setOnClickListener(this)
            //判断是否来自收藏夹
            binding.tvDel.visibility = if (bean.isFromCollect) View.VISIBLE else View.GONE
            binding.tvMove.visibility = if (bean.isFromCollect) View.VISIBLE else View.GONE
            binding.llCollect.visibility = if (bean.isFromCollect) View.GONE else View.VISIBLE
            binding.tvDel.setOnClickListener(this)
            //移动
            binding.tvMove.setOnClickListener(this)
        }

        viewModel.reqAddShareCount(bean.id, 2)
    }

    override fun onClick(v: View) {

        when (v.id) {
            R.id.backImageView -> {
                finish()
            }
            R.id.tv_open -> {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return
                }
                if (alawaysdownloadList.size > 0) {
                    if (FileUtils.fileIsExists(alawaysdownloadList[0].path)) {
                        DownloadLimitManager.openFile(this, File(alawaysdownloadList[0].path))
                    } else {
                        ToastUtils.showShort(this, "文件已删除")
                    }
                }
            }
            R.id.tv_download -> {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return
                }
                PermissionsUtils.getInstance().chekPermissions(this, PermissionCollection.FILE.getPermissionList(), object : PermissionsCall() {
                    override fun permissionsPass() {
                        //点击下载
                        viewModel.reqMaterialAuthenticity(bean.id, object : APIResponse<Boolean>(this) {
                            override fun onSuccess(result: Boolean?, json: String?) {
                                viewModel.reqAddShareCount(bean.id, 0)
                                MaterialConstants.downloadFile(this@DocumentDetailActivity, bean.fileUrl, "${bean.name}.${bean.desc}", bean.thumbnail, bean.fileSize, bean.type)
                            }
                        })
                    }
                })
            }
            R.id.tv_share -> {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return
                }
                viewModel.shareMaterial(this, bean.id, bean.name, bean.thumbnail, true, TabConfigure.IMG.tabConfig)
            }
            R.id.ll_collect -> {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return
                }
                //点击收藏
                collectOrCancel()
            }
            R.id.tv_del -> {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return
                }
                //删除
                collectOrCancel(true)
            }
            R.id.tv_move -> {
                if (DoubleClickHelper.isOnDoubleClick()) {
                    HKToastUtils.showToast("请勿频繁操作")
                    return
                }
                //移动
                moveOption()
            }
        }
    }

    //移动操作
    private fun moveOption() {
        viewModel.moveMaterial(this, this, bean.id, bean.collectionFolderId, object : APIResponse<Boolean>(this) {

            override fun onSuccess(result: Boolean?, json: String) {
                ToastUtils.showShort(this@DocumentDetailActivity, "移动成功")
                EventBusUtils.sendNotify1Value(MessageBus.msgId_material_detCollection, TabConfigure.FILE.tabConfig)
                EventBusUtils.sendNotify1Value(MessageBus.msgId_material_moveCollection, TabConfigure.FILE.tabConfig)
                finish()
            }

            override fun onFailed(message: String) {
                //                    super.onFailed(message);
                ToastUtils.showShort(this@DocumentDetailActivity, "网络异常，移动失败")
            }
        })
    }

    //收藏。取消收藏
    private fun collectOrCancel(isDel: Boolean = false) {
        if (bean.isHasCollect == 1) {
            //已收藏--->取消收藏
            viewModel.loadCancelCollection(bean.collectionFolderId, bean.id, object : APIResponse<Boolean>(this) {
                override fun onSuccess(result: Boolean?, json: String?) {
                    bean.isHasCollect = 0
                    binding.imgCollectCancel.isSelected = false
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_collect_or_cancel, 0)
                    if (bean.isFromCollect) {
                        EventBusUtils.sendNotify1Value(MessageBus.msgId_material_detCollection, TabConfigure.FILE.tabConfig)
                        EventBusUtils.sendNotify1Value(MessageBus.msgId_material_moveCollection, TabConfigure.FILE.tabConfig)
                    }
                    if (isDel) {
                        ToastUtils.showShort(this@DocumentDetailActivity, "删除成功")
                        finish()
                    } else {
                        ToastUtils.showShort(this@DocumentDetailActivity, "已取消收藏")
                    }
                }

                override fun onFailed(message: String?) {
                    ToastUtils.showShort(this@DocumentDetailActivity, "网络异常，取消收藏失败")
                }
            })
        } else {
            //未收藏--->收藏
            viewModel.collectionMaterial(this@DocumentDetailActivity, this@DocumentDetailActivity, bean.id, object : APIResponse<CreateFolderBean>(this) {
                override fun onSuccess(result: CreateFolderBean?, json: String?) {
                    ToastUtils.showShort(this@DocumentDetailActivity, "收藏成功")
                    bean.isHasCollect = 1
                    binding.imgCollectCancel.isSelected = true
                    EventBusUtils.sendNotify1Value(MessageBus.msgId_collect_or_cancel, 1)
                    mSensorsDataManager.materialCollection(bean.name, MaterialConstants.MATERIAL_FILE)
                }

                override fun onFailed(message: String?) {
                    ToastUtils.showShort(this@DocumentDetailActivity, "网络异常，收藏失败")
                }
            })
        }
    }

    val alawaysdownloadList = mutableListOf<DownloadInfo>()
    private fun isAlwaysDownload() {
        alawaysdownloadList.clear()
        val downloadList = DBManager.getInstance()
            .getDownloadList(SpUtils.getInstance().userId, false)
        for (datainfo in downloadList) {
            if (datainfo.url.equals(bean.fileUrl)) {
                //已下载过
                alawaysdownloadList.add(datainfo)
            }
        }
        binding.tvOpen.visibility = if (alawaysdownloadList.size > 0) View.VISIBLE else View.GONE
        binding.tvDownload.visibility = if (alawaysdownloadList.size == 0) View.VISIBLE else View.GONE
    }

    override fun onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
        mSensorsDataManager.materialLook(bean.name, MaterialConstants.MATERIAL_FILE, mSensorsDataManager.getBrowseTime())
        super.onDestroy()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun update(info: DownloadInfo) {
        if (DownloadInfo.DOWNLOAD_OVER == info.downloadStatus) {//下载完成
            isAlwaysDownload()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(messageBus: MessageBus) {
        if (messageBus.codeType == MessageBus.msgid_start_download) {//点击下载
//            isAlwaysDownload()
        } else if (messageBus.codeType == MessageBus.msgId_material_createFolder) {
            if (viewModel.createFolderListener != null) {
                viewModel.createFolderListener?.onCreateFolder(messageBus.param1 as FolderListBean)
            }
        }
    }

}